package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.SubAccountLoginDTO;
import com.sky.entity.Employee;
import com.sky.entity.SubAccounts;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.SubAccountsMapper;
import com.sky.service.SubAccountsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.service.WalletsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author GHOSTER by RemSynch
 * @since 2024-10-24
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
@Slf4j
public class SubAccountsServiceImpl extends ServiceImpl<SubAccountsMapper, SubAccounts> implements SubAccountsService {

    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int USERNAME_LENGTH = 10;
    private static final int PASSWORD_LENGTH = 8;

    @Autowired
    private WalletsService walletsService;
    @Autowired
    private SubAccountsMapper subAccountsMapper;

    @Override
    @Transactional
    public Boolean createRandomUser(BigDecimal bigDecimal) {
        String username = generateRandomString(USERNAME_LENGTH);
        String password = generateRandomString(PASSWORD_LENGTH);

        SubAccounts user = new SubAccounts();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone("1234567890"); // 可以替换为随机生成的电话号码
        user.setCreateTime(LocalDateTime.now());
        user.setIsDeleted(0); // 未删除状态
        log.info("Generated username: {}", username);
        log.info("Generated password: {}", password);
        log.info("user：{}", user);

        // 保存用户
        if (!this.save(user)) {
            return false; // 用户保存失败
        }

        LambdaQueryWrapper<SubAccounts> qw = new LambdaQueryWrapper<>();
        SubAccounts userInDB = this.getOne(qw.eq(SubAccounts::getUsername, username));

        // 创建钱包并记录交易
        try {
            walletsService.createWalletAndRecordTransaction(user.getId(), bigDecimal, userInDB.getId());
        } catch (Exception e) {
            // 处理异常，可能是钱包创建或交易记录失败
            throw new RuntimeException("Failed to create wallet and record transaction", e);
        }

        return true; // 用户和钱包创建成功
    }

    public SubAccounts login(SubAccountLoginDTO subAccountLoginDTO) {
        String username = subAccountLoginDTO.getUsername();
        String password = subAccountLoginDTO.getPassword();

        // 1、根据用户名查询数据库中的数据
        SubAccounts accounts = subAccountsMapper.getByUsername(username);

        // 2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (accounts == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 密码比对
        if (!password.equals(accounts.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(accounts.getIsDeleted(), 1)) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 3、返回实体对象
        return accounts;
    }

    // 随机字符串生成方法
    private String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }
}

